package hkr.se1.cyvasse;

import Game.Game;
import Game.Tile;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;

public class BoardViewAdapter extends BaseAdapter {

	private Context context;
	private Tile[][] board;
	private int[] tileIdArray;
	private int[] pieceIdArray;
	private Game game;

	public BoardViewAdapter(Context context, Game game) {
		this.context = context;
		this.game = game;
		board = game.getBoard();
		tileIdArray = createTileIDArray();
		pieceIdArray = createPieceIDArray();
	}

	@Override
	public int getCount() {
		return 64;
	}

	@Override
	public Object getItem(int index) {
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		TileView tileView;

		if (convertView == null) {
			tileView = new TileView(context, game);
			tileView.setLayoutParams(new GridView.LayoutParams(50, 50));
		} else {
			tileView = (TileView) convertView;
		}
		tileView.setTileImage(tileIdArray[position]);
		tileView.setPieceImage(pieceIdArray[position]);
		tileView.setId(position);
		tileView.setPadding(1, 1, 1, 1);
		return tileView;
	}

	private int[] createTileIDArray() {

		int counter = 0;

		int[] returnArray = new int[64];
		for (int i = 0; i < 8; i++) {
			for (int j = 0; j < 8; j++) {
				returnArray[counter] = board[i][j].getImageId();
				counter++;
			}
		}

		return returnArray;
	}

	private int[] createPieceIDArray() {

		int counter = 0;

		int[] returnArray = new int[64];
		for (int i = 0; i < 8; i++) {
			for (int j = 0; j < 8; j++) {
				if (board[i][j].getPiece() != null) {
					returnArray[counter] = board[i][j].getPiece().getImageId();
				}
				counter++;
			}
		}

		return returnArray;
	}
}
